package com.efounder.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.efounder.util.AppContext;
import com.utilcode.util.ZipUtils;
import com.zhuiji7.filedownloader.download.DownLoadListener;
import com.zhuiji7.filedownloader.download.DownLoadManager;
import com.zhuiji7.filedownloader.download.DownLoadService;
import com.zhuiji7.filedownloader.download.dbcontrol.FileHelper;
import com.zhuiji7.filedownloader.download.dbcontrol.bean.SQLDownLoadInfo;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by lch on 2016/8/25 0025.
 * //TODO 待思考的问题：1.这个断点续传组件的进度是由数据库控制的，是否会出现，数据库的进度与本地已经下载的文件不一致的情况？2.这个断点续传的组件用的地方有apk、res、公众号更新，有很多地方是重复的，是否可以抽出一个父类？
 */

public class PublicAccoutDown {


    private String publicAccoutDownUrl;
    private Context mContext;
    private String TAG = "PublicAccoutDown";
    private PublicAccoutDownInterface publicAccoutDownInterface;
    /*使用DownLoadManager时只能通过DownLoadService.getDownLoadManager()的方式来获取下载管理器，不能通过new
    DownLoadManager()的方式创建下载管理器*/
    private DownLoadManager manager;

    private static float lastScale, nowScale;
    private static boolean isPaused = false;
    private static String fileName;


    public PublicAccoutDown(Context context) {
        mContext = context;

    }

    public void start(String _publicAccoutDownUrl, PublicAccoutDownInterface
            _publicAccoutDownInterface) {


        this.publicAccoutDownUrl = _publicAccoutDownUrl;
        this.publicAccoutDownInterface = _publicAccoutDownInterface;

        fileName = publicAccoutDownUrl.substring(publicAccoutDownUrl.lastIndexOf("/") + 1);

        startDownLoad();
    }

    private void startDownLoad() {
        /*获取下载管理器*/
        manager = DownLoadService.getDownLoadManager();

        if (manager == null){
            return;
        }

        /*设置用户ID，客户端切换用户时可以显示相应用户的下载任务*/
        manager.changeUser("PublicAccount");

        /*断点续传需要服务器的支持，设置该项时要先确保服务器支持断点续传功能*/
        manager.setSupportBreakpoint(true);

        //TODO 每次都下载
        File downloadFile = new File(FileHelper.getFileDefaultPath() + "/(" + FileHelper
                .filterIDChars(fileName) + ")" + fileName);
        if (downloadFile.exists()) {
            downloadFile.delete();
        }


        //info.setOnDownloading(true);
        /*将任务添加到下载队列，下载器会自动开始下载*/
        int i = manager.addTask(fileName, publicAccoutDownUrl, fileName);

        final Timer timerFresh = new Timer();
        timerFresh.schedule(new TimerTask() {
            public void run() {
                if (lastScale == nowScale && !isPaused && nowScale != 0) {

                    downErrorHandler.sendEmptyMessage(0);
                    // Toast.makeText(mContext, "网络不稳定", 200).show();
                }
                nowScale = lastScale;
                if ((int) (lastScale * 100) == 100)
                    timerFresh.cancel();
            }
        }, 1000, 10000);


        DownLoadListener downLoadListener = new DownLoadListener() {
            @Override
            public void onStart(SQLDownLoadInfo sqlDownLoadInfo) {
                // checkAppVersionUtilInterface.startDown(0);
            }

            @Override
            public void onProgress(SQLDownLoadInfo sqlDownLoadInfo, boolean
                    isSupportBreakpoint) {

                float lastScale = (float) sqlDownLoadInfo.getDownloadSize() / sqlDownLoadInfo
                        .getFileSize();
                Message message = new Message();
                message.arg1 = (int) (lastScale * 100);
                downProgressHandler.sendMessage(message);//发送message信息
            }

            @Override
            public void onStop(SQLDownLoadInfo sqlDownLoadInfo, boolean isSupportBreakpoint) {
                publicAccoutDownInterface.stop();

            }

            @Override
            public void onError(SQLDownLoadInfo sqlDownLoadInfo) {
                publicAccoutDownInterface.error();

                //如果出现其他类型的异常，会删除这条任务及cache文件，并重新启动任务
                manager.deleteTask(fileName);
                int i = manager.addTask(fileName, publicAccoutDownUrl, fileName);
                manager.setSingleTaskListener(fileName, this);
                manager.startTask(manager.getCurrentTask());
            }

            @Override
            public void onSuccess(SQLDownLoadInfo sqlDownLoadInfo) {
                mContext.stopService(new Intent(mContext, DownLoadService.class));
                final String TEMP_FILEPATH = FileHelper.getFileDefaultPath();
                String filePath = TEMP_FILEPATH + "/(" + FileHelper.filterIDChars
                        (sqlDownLoadInfo.getFileName()) + ")" + sqlDownLoadInfo.getFileName();
                publicAccoutDownInterface.downloadOver(filePath);
            }

            @Override
            public void onNetError(SQLDownLoadInfo sqlDownLoadInfo) {
                try {
                    Thread.sleep(3000);
                    manager.startTask(manager.getCurrentTask());
                } catch (Exception e) {
                }
            }
        };

        manager.setSingleTaskListener(fileName, downLoadListener);
        //如果已经下载完毕
        if (i == -1) {

            final String TEMP_FILEPATH = FileHelper.getFileDefaultPath();
            String filePath = TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(fileName) + ")"
                    + fileName;
            publicAccoutDownInterface.downloadOver(filePath);
        } else {

//                float progressnum  = ((float) info.getDownFileSize() / info
//                        .getFileSize()) * 100;
//                if((int)progressnum == 100){
//                    manager.deleteTask(fileName);
//                    manager.addTask(fileName, publicAccoutDownUrl, fileName);
//                    info.setOnDownloading(true);
//                    manager.setSingleTaskListener(fileName,downLoadListener);
//                }
            manager.startTask(fileName);
//                publicAccoutDownInterface.startDown(((float) info.getDownFileSize() / info
//                        .getFileSize()) * 100);

        }

    }

    public void stopTask() {
        if (manager != null)
            manager.stopTask(fileName);
        isPaused = true;
        AppContext.getInstance().stopService(new Intent(AppContext.getInstance(), DownLoadService.class));

    }

    public void startTaskID() {
        manager.startTask(fileName);
        isPaused = false;
    }

    /**
     * 解压文件
     */
    public void unzipAndEncryptFile(final String filePath, final String taskfilePath) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                FileHelper.copyFile(filePath, taskfilePath);

                //删除原有的解压缩后的文件
                //deleteUnzipRes();
                boolean issuccessZip;


                //将更新的zip解压到临时目录
                String taskbasefolderUrl = taskfilePath.substring(0, taskfilePath.lastIndexOf
                        ("/") + 1);
                File taskbasefolder = new File(taskbasefolderUrl);
                if (!taskbasefolder.exists()) {
                    try {
                        taskbasefolder.mkdir();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                //19.03.19，替换使用AndroidUtils库里的解压方法
                try {
                    List<File> files = ZipUtils.unzipFile(taskfilePath, taskbasefolderUrl);
                    issuccessZip = files.size() > 0;
                } catch (Exception e) {
                    e.printStackTrace();
                    issuccessZip = false;
                }


                if (issuccessZip) {
                    //资源文件下载并处理完毕 ,添加标志文件
                    File file = new File(taskfilePath + "/" + "0.0.1");
                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (Exception e) {

                        }

                    }
                    deleteFile(filePath);
                    deleteFile(taskfilePath);

                    publicAccoutDownInterface.unZIPOVER();
                }

            }
        }).start();

    }

    private void deleteFile(String filePath) {
        File deleteFile = new File(filePath);
        if (deleteFile.exists()) {
            deleteFile.delete();
        }
    }

    private Handler downErrorHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(mContext, "网络不稳定。", Toast.LENGTH_LONG).show();

        }
    };
    private Handler downProgressHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            publicAccoutDownInterface.updateProgress(msg.arg1);
        }
    };
}



